using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.UserRoles.Commands;
using Identity.Domain.Aggregates;
using MediatR;

namespace Identity.Application.UserRoles.CommandHandlers;

public class ReplaceUserRolesCommandHandler : IRequestHandler<ReplaceUserRolesCommand, Result>
{
    private readonly IUserService _userService;
    private readonly IRoleService _roleService;
    private readonly IUserRoleService _userRoleService;

    public ReplaceUserRolesCommandHandler(IUserRoleService userRoleService, IUserService userService, IRoleService roleService)
    {
        _userRoleService = userRoleService;
        _roleService = roleService;
        _userService = userService;
    }
    public async Task<Result> Handle(ReplaceUserRolesCommand request, CancellationToken cancellationToken)
    {
        var userData = await _userService.GetUserByIdAsync(request.userId);

        var roles = new List<Role>();
        foreach (var roleId in request.roleIds)
        {
            var roleData = await _roleService.GetRoleByIdAsync(roleId);
            roles.Add(Role.LoadFromPersistence(roleData!.Id,roleData.Code, roleData.Name,roleData.PermissionIds, roleData.Description,roleData.Status));
        }

        var user = UserAggregate.LoadFromPersistence(userData!.Id, userData.UserName, userData.Email, userData.Roles.ToList());

        user.ClearRoles();

        foreach (var role in roles)
        {
            user.AddRoles(role.Name); ;
        }

        var result = await _userRoleService.ReplaceRolesAsync(request.userId, request.roleIds);
        if (!result) return Result.Failure("替换角色失败");

        return Result.Success();
    }
}